import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, message, Modal, Dropdown, Image, Typography, Upload } from 'antd';
import { PlusOutlined, DeleteOutlined, MoreOutlined, DownloadOutlined, EyeOutlined, UploadOutlined } from '@ant-design/icons';
import { getFileList, deleteFile, batchDeleteFiles } from '@/services/systemManagementApi';
import FileUploadModal from './components/FileUploadModal';
import FilePreview from './components/FilePreview';
import moment from 'moment';

const { Text } = Typography;

const FileList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [currentFile, setCurrentFile] = useState<SYSTEM.FileUploadModel | undefined>();

  // 文件类型标签颜色映射
  const typeColorMap = {
    image: 'green',
    audio: 'blue',
    video: 'purple',
    document: 'orange',
    other: 'default',
  };

  // 使用类型标签颜色映射
  const usageTypeColorMap = {
    avatar: 'cyan',
    course_cover: 'geekblue',
    banner: 'magenta',
    audio: 'blue',
    video: 'purple',
    document: 'orange',
    other: 'default',
  };

  // 表格列定义
  const columns: ProColumns<SYSTEM.FileUploadModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '文件预览',
      dataIndex: 'file_url',
      width: 120,
      search: false,
      render: (_, record) => {
        if (record.file_type === 'image') {
          return (
            <Image
              src={record.file_url}
              alt={record.original_name}
              width={80}
              height={60}
              style={{ objectFit: 'cover', borderRadius: 4 }}
              fallback=""
            />
          );
        }
        return (
          <div style={{
            width: 80,
            height: 60,
            background: '#f5f5f5',
            borderRadius: 4,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '12px',
            color: '#999'
          }}>
            {record.file_type.toUpperCase()}
          </div>
        );
      },
    },
    {
      title: '文件名称',
      dataIndex: 'original_name',
      width: 200,
      ellipsis: true,
      copyable: true,
      render: (text) => (
        <Text style={{ maxWidth: 180 }} ellipsis={{ tooltip: text }}>
          {text}
        </Text>
      ),
    },
    {
      title: '文件类型',
      dataIndex: 'file_type',
      width: 100,
      valueType: 'select',
      valueEnum: {
        image: { text: '图片', status: 'Success' },
        audio: { text: '音频', status: 'Processing' },
        video: { text: '视频', status: 'Warning' },
        document: { text: '文档', status: 'Error' },
        other: { text: '其他', status: 'Default' },
      },
      render: (_, record) => {
        const typeMap = {
          image: '图片',
          audio: '音频',
          video: '视频',
          document: '文档',
          other: '其他',
        };
        return (
          <Tag color={typeColorMap[record.file_type]}>
            {typeMap[record.file_type]}
          </Tag>
        );
      },
    },
    {
      title: '使用类型',
      dataIndex: 'usage_type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        avatar: { text: '头像', status: 'Default' },
        course_cover: { text: '课程封面', status: 'Processing' },
        banner: { text: '轮播图', status: 'Warning' },
        audio: { text: '音频文件', status: 'Success' },
        video: { text: '视频文件', status: 'Error' },
        document: { text: '文档文件', status: 'Default' },
        other: { text: '其他', status: 'Default' },
      },
      render: (_, record) => {
        const usageMap = {
          avatar: '头像',
          course_cover: '课程封面',
          banner: '轮播图',
          audio: '音频文件',
          video: '视频文件',
          document: '文档文件',
          other: '其他',
        };
        return (
          <Tag color={usageTypeColorMap[record.usage_type]}>
            {usageMap[record.usage_type]}
          </Tag>
        );
      },
    },
    {
      title: '文件大小',
      dataIndex: 'file_size',
      width: 100,
      search: false,
      render: (size) => {
        if (!size) return '-';
        if (size < 1024) return `${size}B`;
        if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`;
        if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)}MB`;
        return `${(size / (1024 * 1024 * 1024)).toFixed(1)}GB`;
      },
    },
    {
      title: '上传者',
      dataIndex: 'uploader_name',
      width: 120,
      search: false,
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 150,
      search: false,
      ellipsis: true,
      render: (desc) => desc || '-',
    },
    {
      title: '上传时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="preview"
          type="link"
          size="small"
          onClick={() => handlePreview(record)}
        >
          预览
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'download',
                label: '下载',
                icon: <DownloadOutlined />,
                onClick: () => handleDownload(record),
              },
              {
                key: 'copy',
                label: '复制链接',
                onClick: () => handleCopyUrl(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理预览
  const handlePreview = (record: SYSTEM.FileUploadModel) => {
    setCurrentFile(record);
    setPreviewVisible(true);
  };

  // 处理下载
  const handleDownload = (record: SYSTEM.FileUploadModel) => {
    const link = document.createElement('a');
    link.href = record.file_url;
    link.download = record.original_name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('文件下载开始');
  };

  // 处理复制链接
  const handleCopyUrl = (record: SYSTEM.FileUploadModel) => {
    navigator.clipboard.writeText(record.file_url).then(() => {
      message.success('文件链接已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 处理删除
  const handleDelete = (record: SYSTEM.FileUploadModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件 "${record.original_name}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteFile(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的文件');
      return;
    }

    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个文件吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await batchDeleteFiles(selectedRowKeys);
          message.success('批量删除成功');
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        } catch (error) {
          message.error('批量删除失败');
        }
      },
    });
  };

  return (
    <PageContainer>
      <ProTable<SYSTEM.FileUploadModel>
        headerTitle="文件管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="upload"
            type="primary"
            icon={<UploadOutlined />}
            onClick={() => setUploadModalVisible(true)}
          >
            上传文件
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space size={16}>
            <a onClick={handleBatchDelete}>批量删除</a>
          </Space>
        )}
        request={async (params, sort) => {
          const response = await getFileList({
            page: params.current,
            limit: params.pageSize,
            filename: params.original_name,
            file_type: params.file_type,
            usage_type: params.usage_type,
            uploader: params.uploader_name,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 文件上传弹窗 */}
      <FileUploadModal
        visible={uploadModalVisible}
        onCancel={() => setUploadModalVisible(false)}
        onSuccess={() => {
          setUploadModalVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 文件预览弹窗 */}
      <FilePreview
        visible={previewVisible}
        file={currentFile}
        onCancel={() => setPreviewVisible(false)}
      />
    </PageContainer>
  );
};

export default FileList;
